﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jacobi.Vst.Core;

namespace KinectedMusic.Audio
{
    public class Notes
    {
        List<int> bar = new List<int>();
        List<Note> notes = new List<Note>();
        double barLoops = 4; // TODO: what is the best way to do this
        double nextPosition = 0; // TODO: do it another way
        // TODO: this should be done another way
        public void AddNote(byte note, double length, byte velocity)
        {
            double start = nextPosition % barLoops;
            notes.Add(new Note(note, start, length, velocity));
        }

       
        public void AddNote(byte note, double start, double length)
        {
            start = start % barLoops;
            notes.Add(new Note(note, start, length, 127));
        }

        // TODO: Not needed? just use clear notes
        //public void RemoveNote(byte note, double start, double length)
        //{
        //}

        public VstEvent[] GetMIDIEvents(double position, double barStep, int bufferSize)
        {

            double start = position;
            double end = position + barStep;
            nextPosition = end;
            end = end % barLoops;
            start = start % barLoops;

            // TODO: Test??
            if (end < start)
            {
                end += barLoops;
            }

            List<VstEvent> MIDIEvents = new List<VstEvent>();
            //TODO: Don't use a for each.. for threads?
            foreach (Note note in notes)
            {
                //TODO: should make faster, no need to calculate... maybe even order the notes...
                double noteEnd = note.start + note.length;

                // TODO have dif ifs if start < end... test what I wrote... it might work
                if (note.start >= start && note.start < end)
                {
                    int offSet = (int)(((note.start - start) / barStep) * bufferSize);
                    Console.WriteLine(offSet);
                    MIDIEvents.Add(new VstMidiEvent(offSet, 10, 0, new byte[] { 144, note.note, note.velocity, 0 }, 0, 0));
                }
                if (noteEnd > start && noteEnd <= end)
                {
                    int offSet = (int)(((noteEnd - start) / barStep) * bufferSize);
                    MIDIEvents.Add(new VstMidiEvent(offSet, 10, 0, new byte[] { 144, note.note, 0, 0 }, 0, 0));
                }
            }

            return MIDIEvents.ToArray();
        }

    }
}
